<template>
  <el-breadcrumb class="app-breadcrumb" separator="/">
    <!-- item.path 可能是一个路由参数导航 /test/index/:id -->
    <el-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
      <span
        v-if="item.redirect === 'noRedirect' || index == levelList.length - 1"
        class="no-redirect"
        >{{ item.meta?.title }}</span
      >
      <a v-else @click.prevent="handleLink(item)">{{ item.meta?.title }}</a>
    </el-breadcrumb-item>
  </el-breadcrumb>
</template>

<script setup lang="ts">
import { compile } from 'path-to-regexp'
import type { RouteLocationMatched } from 'vue-router'
import { useSttingStore } from '@/stores/settings'

const settingsStore = useSttingStore()
const theme = computed(() => settingsStore.settings.theme)

type PartialRouteLocationMatched = Partial<RouteLocationMatched>

const Route = useRoute()
const Router = useRouter()
const levelList = ref<PartialRouteLocationMatched[]>([])

const getBreadcrumb = () => {
  let matched = Route.matched.filter(
    (item) => item.meta && item.meta.title
  ) as PartialRouteLocationMatched[]

  const first = matched[0]
  if (!isDashboard(first)) {
    matched = [{ path: '/dashboard', meta: { title: '首页' } }, ...matched]
  }
  levelList.value = matched.filter(
    (item) => item.meta && item.meta.title && item.meta.breadcrumb !== false
  )
}

const isDashboard = (route: PartialRouteLocationMatched) => {
  const name = route && route.name
  if (!name || typeof name !== 'string') return false
  return name.trim().toLocaleLowerCase() === 'Dashboard'.toLocaleLowerCase()
}
watch(() => Route.path, getBreadcrumb, { immediate: true })

// 根据面包屑导航 和 当前访问的路径 生成 跳转路径
function pathCompile(path: string) {
  const { params } = Route
  var toPath = compile(path)
  return toPath(params)
}
function handleLink(route: PartialRouteLocationMatched) {
  const { redirect, path } = route
  console.log(redirect, path)

  Router.push(pathCompile(path!))
}
</script>

<style lang="scss" scoped>
@use '@/styles/variables.module.scss' as *;
.app-breadcrumb.el-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;
  color: #fff !important;
  :deep(.el-breadcrumb__inner) {
    a {
      color: $colorWhite;
      &:hover {
        color: v-bind(theme);
      }
    }
  }
  .no-redirect {
    color: #97a8be;
    cursor: text;
  }
}
</style>
